from datetime import datetime

from django.shortcuts import render,HttpResponse

import article.views
from .models import User,Article

# Create your views here.
def article_test(request):
    user    = User(username="zhangsan",password="123456")
    user.save()
    article = Article(title="chatgpt5",content="这里是 chatgpt 已经发布",author=user)
    article.save()
    return HttpResponse("article_test 测试测试")

## 获取 article
def get_articles(request):
    article = Article.objects.first()
    return HttpResponse(f"姓名：{article.author.username},标题：{article.title}")

## 1对多 演示
def ontomany(request):
    user = User.objects.first()
    #articles = user.article_set.all()
    articles = user.article.filter(title__contains="chat").all()
    for article in articles: print(article.title)
    return HttpResponse("一对多演示")

## 查询方法
def query1(request):
    article = Article.objects.filter(id__in=[1,2,3,4])
    print(article.query)  ## 查看执行的 sql 语句
    print(article)
    for item in article:
        print(item.title)
        print(item.content)
        print(item.author.username)
    return HttpResponse("query1")


## range
def query2(request):
    start_date = datetime(year=2025,month=7,day=21)
    end_date   = datetime(year=2025,month=7,day=22)
    articles = Article.objects.filter(pub_time__range=(start_date,end_date))
    print(articles.query)
    print(articles)
    return HttpResponse("query2")


## 关联查询
def query3(request):
    user = User.objects.filter(article111__title__contains="包")
    print(user.query)
    print(user)
    return HttpResponse("query3")